<template>
  <div class="users-page">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="ipt">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="query"
            clearable
            @clear="clearFn"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getList"
            ></el-button>
          </el-input>
        </div>
        <el-button type="primary" @click="isDialogFormShow('add')"
          >添加用户</el-button
        >
      </div>
      <el-table border :data="list">
        <el-table-column type="index" width="50" label="序号">
        </el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-switch
              :value="true"
              v-model="row.mg_state"
              @change="stateChange(row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="isDialogFormShow('edit', row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delUserInfo(row.id)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="isDialogFormShow('allocation', row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[1, 3, 5, 10]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="changeSize"
        >
        </el-pagination>
      </div>
    </el-card>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      @close="dialogClose"
    >
      <div v-if="dialogType === 'allocation'" class="allocation">
        <div class="text">当前用户：{{ editForm.username }}</div>
        <div class="text">当前角色：{{ roleName }}</div>
        <div class="text">
          <span>分配新角色：</span>
          <el-select v-model="value" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
      </div>
      <el-form
        v-else-if="dialogType === 'edit'"
        :model="editForm"
        label-width="70px"
        :rules="rules"
        ref="form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <el-form
        v-else
        :model="form"
        label-width="70px"
        :rules="rules"
        ref="form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="form.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import {
  allocationApi,
  createListApi,
  delListApi,
  updateListApi,
} from "@/api/e-commerce";
import { Message } from "element-ui";

const mapTitle = {
  add: "添加用户",
  allocation: "分配角色",
  edit: "修改用户",
};
export default {
  name: "UsersIndex",
  data() {
    return {
      loading: false,
      query: "",
      options: [
        {
          value: "选项1",
          label: "主管",
        },
        {
          value: "选项2",
          label: "人事",
        },
        {
          value: "选项3",
          label: "组长",
        },
        {
          value: "选项4",
          label: "普通员工",
        },
        {
          value: "选项5",
          label: "管理员",
        },
      ],
      value: "",
      list: [],
      input: "",
      pagenum: 1,
      pagesize: 1,
      total: 0,
      dialogFormVisible: false,
      form: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      dialogType: "",
      rules: {
        username: [
          { required: true, message: "请输入用户名" },
          { min: 2, max: 10, message: "长度需要在2都10之间" },
        ],
        password: [
          { required: true, message: "请输入密码" },
          { pattern: /^\w{6,15}$/, message: "长度需要在6都15之间" },
        ],
        email: [
          { required: true, message: "请输入邮箱" },
          {
            pattern:
              /^[A-Za-z0-9]+([_.][A-Za-z0-9]+)*@([A-Za-z0-9-]+\.)+[A-Za-z]{2,6}$/,
            message: "请输入合法的邮箱",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号" },
          {
            pattern:
              /^((\+|00)86)?((134\d{4})|((13[0-3|5-9]|14[1|5-9]|15[0-9]|16[2|5|6|7]|17[0-8]|18[0-9]|19[0-2|5-9])\d{8}))$/,
            message: "请输入合法的手机号",
          },
        ],
      },
      editForm: {},
      roleName: "",
    };
  },
  created() {
    this.getList();
  },
  computed: {
    dialogTitle() {
      return mapTitle[this.dialogType];
    },
  },
  methods: {
    // 搜索框清除按钮
    clearFn() {
      this.getList();
    },
    // 关闭对话框
    dialogClose() {
      // 清空form
      this.form = {};
      // 判断是否有表单，有的话重置表单
      if (this.dialogType !== "allocation") {
        this.$refs.form.resetFields();
      }
    },
    // 更改用户状态
    async stateChange(userInfo) {
      try {
        this.loading = true;
        await request.put(
          `/api/private/v1/users/${userInfo.id}/state/${userInfo.mg_state}`
        );
        // console.log(res);
        Message.success("修改状态成功");
        this.loading = false;
      } catch (err) {
        this.loading = false;
        Message.error("修改状态失败");
        userInfo.mg_state = !userInfo.mg_state;
      }
      // if (res.meta.status !== 200) {
      //   Message.error("修改状态失败");
      //   userInfo.mg_state = !userInfo.mg_state;
      // }
    },
    async submit() {
      try {
        // if (this.dialogType === "allocation") {
        //
        // }
        // 校验表单

        this.loading = true;
        // console.log("触发提交事件");
        if (this.dialogType === "edit") {
          // const { id, email, mobile } = this.editForm;
          // const res = await editListApi({
          //   id,
          //   email,
          //   mobile,
          // });
          await this.$refs.form.validate();
          await request.put("/api/private/v1/users/" + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          });
          this.dialogFormVisible = false;
          Message.success("修改成功");
          this.getList();
          this.loading = false;
        } else if (this.dialogType === "add") {
          await this.$refs.form.validate();
          await createListApi(this.form);
          this.loading = true;
          Message.success("添加成功");
          this.dialogFormVisible = false;
          this.getList();
          this.loading = false;
        } else {
          const res = await allocationApi(this.editForm.id, this.editForm.rid);
          Message.success("分配成功");
          console.log(res);
          this.dialogFormVisible = false;
          this.getList();
        }
      } catch (err) {
        this.loading = false;
        Message.error("操作失败");
        console.log(err);
      }
    },
    // 根据传过来type，展示相应的对话框
    async isDialogFormShow(type, row) {
      this.dialogFormVisible = true;
      this.dialogType = type;
      if (type !== "add") {
        const { data: res } = await request.get(
          "/api/private/v1/users/" + row.id
        );
        console.log(res);
        this.editForm = res.data;
        // console.log(row);
        this.roleName = row.role_name;
      }
    },
    // 删除功能
    async delUserInfo(id) {
      this.loading = true;
      try {
        await this.$confirm("此操作将删除该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        await delListApi(id);

        this.getList();
        // this.dialogFormVisible = false;
        Message.success("删除成功");
        this.loading = false;
      } catch (err) {
        this.loading = false;
        Message.info("已取消删除");
        console.log(err);
      }
    },
    // 一页展示的size
    changeSize(value) {
      this.pagesize = value;
      this.getList();
    },
    // 跳转到相应页码
    handleCurrentChange(value) {
      this.pagenum = value;
      this.getList();
    },
    async getList() {
      const res = await updateListApi({
        query: this.query,
        pagenum: this.pagenum,
        pagesize: this.pagesize,
      });
      console.log(res);
      this.list = res.data.data.users;
      this.total = res.data.data.total;
    },
  },
};
</script>

<style lang="scss" scoped>
.users-page {
  .el-breadcrumb {
    margin-bottom: 15px;
  }
  .clearfix {
    display: flex;
    .ipt {
      margin-right: 20px;
    }
  }
  .block {
    margin-top: 15px;
  }
  .allocation {
    font-size: 16px;
    .text {
      margin-bottom: 20px;
    }
  }
  .el-menu {
    border-right: unset;
  }
}
</style>
